import { useState, useEffect, useRef } from 'react';
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    MessageOutlined,
    HistoryOutlined,
    LoginOutlined,
    LogoutOutlined,
    LoadingOutlined,
    PlusOutlined
} from '@ant-design/icons';
import { Button, Input, Modal, Col, Row, Radio, DatePicker, message, Upload, Form, Select, Spin } from 'antd';
import type { UploadChangeParam, RcFile, UploadFile, UploadProps } from 'antd/es/upload';
import type { FormInstance } from 'antd/es/form';
import { useNavigate } from 'react-router-dom'
import './header.scss'
import base from '@/utils/baseUrl'
import { updataUserInfo, getUserInfo } from '@/request/user'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import type { SelectProps } from 'antd';
import { localFilterData } from '@/utils/index'
interface PropsType {
    collapsed?: boolean
    items: any[],
    [propsName: string]: any
}
let timeout: ReturnType<typeof setTimeout> | null;
let currentValue: string;

const Header = (props: PropsType) => {
    const handlefetch = (value: string, callback: any) => {
        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        currentValue = value;
        const fake = () => {
            if (currentValue === value) {
                console.log(currentValue)
                const res = localFilterData(props.items, currentValue, ['key', 'label'])
                setLoading(false)
                callback(res);
            }
        };
        if (value) {
            timeout = setTimeout(fake, 500);
        } else {
            setLoading(false)
            callback([]);
        }
    };
    //基础
    const navigate = useNavigate()
    const { TextArea } = Input
    const token = localStorage.getItem('token')
    const formRef = useRef<FormInstance>(null)
    //用户信息
    const [userinfo, setUserInfo] = useState({
        username: '',
        sex: '',
        account: '',
        balance: 0,
        birthday: '',
        createtime: '',
        email: '',
        handimg: '',
        sign: '',
        hometown: ''
    })
    //用户模态框
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const [searchValue, setSearchValue] = useState<string>()
    const [data, setData] = useState<SelectProps['options']>([]);
    useEffect(() => {
        getUser()
    }, [])
    const upDateUserinfo = () => {//更新用户信息弹窗
        setOpen(true)
        setTimeout(() => {
            formRef.current?.setFieldsValue(userinfo)
        }, 500)
    }
    const handleCancel = () => {    //模态框取消
        setOpen(false);
    };
    const handleOk = () => {    //用户修改确定
        formRef.current?.validateFields().then(value => {
            value.birthday = value.birthday ? dayjs(value.birthday).format('YYYY-MM-DD') : null
            setConfirmLoading(true);
            updataUser(value)
        }).catch(err => console.log(err))
    };
    const getUser = async () => {
        const res = await getUserInfo()
        if (res.status == 200) {
            const { payment_pwd, userid, ...info } = res.data
            info.birthday = info.birthday ? dayjs(new Date(info.birthday)) : null
            setUserInfo(info)
            window.localStorage.setItem('userinfo', JSON.stringify(info))
        }

    }
    //更新用户信息
    const updataUser = async (value: PropsType) => {
        const { createtime, ...info } = value
        const res = await updataUserInfo(info)
        getUser()
        setOpen(false);
        setConfirmLoading(false);
        message.success('更新成功')
    }

    //导航栏搜索
    const onSearch = (e: any) => {
        handlefetch(e, setData);
    }
    const handleChangeNav = (e: any) => {
        const rout = `${e == '/home' ? '' : '/home'}` + e
        setSearchValue(e)
        navigate(rout)
    }
    //上传头像相关
    const [loading, setLoading] = useState(false);
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            const url = info.file.response.data.url
            getUser()
        }
    };

    //退出登录
    const logout = (num: number) => {
        return () => {
            if (!num) {
                localStorage.removeItem('token')
                localStorage.removeItem('userinfo')
            }
            navigate('/login', {
                replace: true
            })

        }
    }
    return (
        <div className="header flex flex-jc-sb plr-20 flex-ai-c">
            <Button
                type="text"
                icon={props.collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={props.changeColl}
                style={{
                    fontSize: '16px'
                }}
            />
            <ul className='flex flex-ai-c'>
                {/* 搜索框 */}
                <li className='flex flex-ai-c'>
                    {/* <Input placeholder="Basic usage" onChange={onSearch} addonAfter={<SearchOutlined />} /> */}
                    <Select
                        onSearch={onSearch}   // onSearch搜索方法
                        onChange={handleChangeNav}  // onChange对搜索出来的下拉选项进行选择的方法
                        value={searchValue}
                        notFoundContent={loading ? <Spin size="small" /> : null}  // notFoundContent当下拉列表为空时显示的内容
                        filterOption={false}    // filterOption：让搜索出来的内容显示列表
                        defaultActiveFirstOption={false}     // 是否默认高亮第一个选项，false不
                        showSearch  // 使下拉选项有搜索的功能
                        style={{ width: '300px' }}     // 控制输入框的长度                                     
                        placeholder="请输入导航名称"
                        options={(data || []).map((d) => ({
                            value: d.key,
                            label: d.label,
                        }))}
                    >
                    </Select>
                </li>
                {/* 头像 */}
                <li className='head-img'>
                    <img onClick={upDateUserinfo} src={userinfo.handimg} title={userinfo.handimg} />
                </li>
                {/* 用户名 */}
                <li>{userinfo.username}</li>
                {/* 消息通知 */}
                <MessageOutlined title='消息' />
                {/* 历史记录 */}
                <HistoryOutlined title='历史记录' />

                {/* 登录操作 */}
                {token ? <LogoutOutlined onClick={logout(0)} title='退出登录' />
                    :
                    <LoginOutlined onClick={logout(1)} title='登录' />}

            </ul>

            <Modal
                title="用户信息"
                open={open}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
                width={'60%'}
            >
                <div className='flex'>
                    <div style={{ marginRight: '10px' }}>
                        <Upload
                            name="file"
                            listType="picture-circle"
                            className="avatar-uploader"
                            showUploadList={false}
                            action={base + '/upload'}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                            data={{ type: 1 }}
                            headers={{ "Authorization": token || '' }}
                        >
                            {userinfo.handimg ? <img style={{ height: '80px', width: '80px', borderRadius: '50%' }} src={userinfo.handimg} alt="avatar" /> : uploadButton}
                        </Upload>
                    </div>
                    <div className='flex flex-dir-c flex-jc-sa'>
                        <p>{userinfo.username}</p>
                        <p>我的余额：{userinfo.balance || 0}</p>
                    </div>
                </div>
                <div style={{ margin: '20px 0' }}>
                    <h3 style={{ margin: '0 0 20px 20px', }}>基本信息</h3>
                    <Form
                        ref={formRef}
                        name="basic"
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        autoComplete="off"
                    >
                        <Row>
                            <Col span={12}>
                                <Form.Item
                                    label="用户名"
                                    name="username"
                                >
                                    <Input placeholder="请输入用户名" />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="手机号"
                                    name="account"
                                    rules={[{ pattern: /^1\d{10}$/, message: '手机号格式错误' }]}
                                >
                                    <Input placeholder="请输入手机号" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12} style={{ color: 'blue' }}>
                                <Form.Item
                                    label="地址管理"
                                >
                                    +新增收获地址
                                </Form.Item>

                            </Col>

                            <Col span={12}>
                                <Form.Item label="注册时间" >
                                    {userinfo.createtime ? userinfo.createtime.split('T')[0] : ''}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row align="middle">
                            <Col span={12}>
                                <Form.Item
                                    label="邮箱"
                                    name="email"
                                >
                                    <Input placeholder="Basic email" />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="性别"
                                    name="sex"
                                >
                                    <Radio.Group>
                                        <Radio value={0}>男</Radio>
                                        <Radio value={1}>女</Radio>
                                    </Radio.Group>
                                </Form.Item>

                            </Col>
                        </Row>

                        <Row align="middle">
                            <Col span={12}>
                                <Form.Item
                                    label="生日"
                                    name="birthday"
                                >
                                    <DatePicker format="YYYY-MM-DD" locale={locale} />
                                </Form.Item>

                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="家乡"
                                    name="hometown"
                                >
                                    <Input placeholder="请输入家乡" />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row align="middle">
                            <Col span={12}>
                                <Form.Item label="个人签名" name="sign">
                                    <TextArea rows={4} showCount placeholder="请输入个性签名" maxLength={100} />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>

                </div>
            </Modal>
        </div>
    )
}
export default Header